//
//  RHMyQRCodeVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/11/7.
//

#import "RHMyQRCodeVC.h"
#import "NetworkConfig.h"
#import "RHTools.h"
#import "AESCrypt.h"

@interface RHMyQRCodeVC ()
@property (nonatomic, strong) UIImageView *qrCodeImageView;

@property (nonatomic, strong) UIImageView *iconImageView;

@property (nonatomic, strong) QMUILabel *nickNameLab;

@property (nonatomic, strong) QMUILabel *roleLab;

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, strong) QMUIButton *saveBtn;
@end

@implementation RHMyQRCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"我的二维码".rh_localized;
    [self setupUI];
    //终端用户本地生成二维码,用于电站转让直接扫描
    if([PrivateMange share].currentUser.orgType == OrganizationTypeUser){
        [self createInviationCode];
    }else{
        [self getInvitationCode];//端点以上,后台获取二维信息,用于给用户绑定
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)setupUI
{
    kWeakSelf;
    UIView *bgView = kView;
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    bgView.layer.masksToBounds = YES;
    [self.view addSubview:bgView];
    self.bgView = bgView;
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(15, 15, kSafe_bottom, 15));
    }];
    //头像
    self.iconImageView = [[UIImageView alloc]init];
    self.iconImageView.layer.cornerRadius = 25;
    self.iconImageView.layer.masksToBounds = YES;
    [bgView addSubview:self.iconImageView];
    [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(kScaleW(50));
        make.centerX.mas_offset(0);
        make.top.mas_offset(30);
    }];
    
    [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:[PrivateMange share].currentUser.avatar] placeholderImage:[UIImage imageNamed:@"kwt_avatar_default"]];
    
    //昵称
    self.nickNameLab = [[QMUILabel alloc]init];
    self.nickNameLab.font = [UIFont systemFontOfSize:17];
    self.nickNameLab.textColor = [UIColor colorWithHexString:@"3F4443" alpha:1];
    self.nickNameLab.text = [PrivateMange share].currentUser.nickName;
    [bgView addSubview:self.nickNameLab];
    [self.nickNameLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.equalTo(weakSelf.iconImageView.mas_bottom).offset(10);
    }];
    
    //角色
    self.roleLab = [[QMUILabel alloc]init];
    self.roleLab.font = [UIFont systemFontOfSize:15];
    self.roleLab.textColor = [UIColor colorWithHexString:@"3F4443" alpha:0.6];
    self.roleLab.text = [RHTools getRoleContentWithType:[PrivateMange share].currentUser.orgType brandId:[PrivateMange share].currentUser.brandId];
    [bgView addSubview:self.roleLab];
    [self.roleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.equalTo(weakSelf.nickNameLab.mas_bottom).offset(10);
    }];
    
    UIImageView *qrBgImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"kwt_qr_border"]];
    [bgView addSubview:qrBgImg];
    [qrBgImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(kScaleW(180));
        make.centerX.mas_offset(0);
        make.centerY.mas_offset(0);
    }];
    
    self.qrCodeImageView = [[UIImageView alloc]init];
    [qrBgImg addSubview:self.qrCodeImageView];
    [self.qrCodeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(15, 15, 15, 15));
    }];
    
    UIImageView *logoImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"kwt_logo"]];
    logoImg.contentMode = UIViewContentModeScaleAspectFit;
    logoImg.backgroundColor = UIColor.whiteColor;
    logoImg.layer.cornerRadius = kScaleW(50)/2.0;
    logoImg.layer.masksToBounds = YES;
    [qrBgImg addSubview:logoImg];
    [logoImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.offset(kScaleW(50));
        make.centerX.mas_offset(0);
        make.centerY.mas_offset(0);
    }];
    
    QMUIButton *saveBtn = [[QMUIButton alloc]init];
    saveBtn.backgroundColor = CMainColorGreen;
    saveBtn.layer.cornerRadius = 8;
    saveBtn.layer.masksToBounds = YES;
    saveBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveBtn setTitle:@"保存到相册".rh_localized forState:UIControlStateNormal];
    [saveBtn setImage:[UIImage imageNamed:@"qrCode_download"] forState:UIControlStateNormal];
    [saveBtn setImagePosition:QMUIButtonImagePositionLeft];
    saveBtn.spacingBetweenImageAndTitle = 5;
    [bgView addSubview:saveBtn];
    self.saveBtn = saveBtn;
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset (15);
        make.right.mas_offset(-15);
        make.bottom.mas_offset(-20);
        make.height.offset(50);
    }];
    [[saveBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        UIImage *image = [weakSelf captureImageFromView:weakSelf.bgView];
        UIImageWriteToSavedPhotosAlbum(image, weakSelf, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }];
    
}

#pragma mark ---- 截屏
-(UIImage *)captureImageFromView:(UIView *)view

{
    self.saveBtn.hidden = YES;
    CGRect imageRectInPDF = CGRectMake(0, 0, view.width*2, view.height*2);

    UIGraphicsImageRenderer *imageRender = [[UIGraphicsImageRenderer alloc]initWithSize:view.size];
    UIImage *chart_Image = [imageRender imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
        [self.bgView.layer renderInContext:rendererContext.CGContext];
    }];
    UIGraphicsBeginImageContext(CGSizeMake(imageRectInPDF.size.width, imageRectInPDF.size.height));
    [chart_Image drawInRect:CGRectMake(0, 0, imageRectInPDF.size.width, imageRectInPDF.size.height)];
    //将图片放大,填满pdf
    UIImage *image_scale = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    self.saveBtn.hidden = NO;
    //用这个方法图片就模糊
//    CGRect screenRect = CGRectMake(0, 0, view.width, view.height);
//
//    UIGraphicsBeginImageContext(screenRect.size);
//
//    CGContextRef ctx = UIGraphicsGetCurrentContext();
//
//    [view.layer renderInContext:ctx];
//
//    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
//
//    UIGraphicsEndImageContext();

    return image_scale;

}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *title = @"";
    NSString *message = @"";
    if (!error) {
           title = @"保存成功".rh_localized;
           message = @"前往相册查看?".rh_localized;
    }else {
           title = @"保存失败".rh_localized;
           message = @"";
    }
       
    // 使用alert view显示二维码保存状态
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:@"photos-redirect://"];
        if([[UIApplication sharedApplication] canOpenURL:url]){
           [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
         }
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:action];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];

}

#pragma mark ---------- 获取加密二维码信息 ------------
-(void)getInvitationCode
{
    [QMUITips showLoadingInView:self.view];
    [BaseModel startWithCompletionAPIKey:H_invitationCode argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [self genarateQRCodeWithContent:request.responseJSONObject[@"data"][@"shareCode"]];
        }
    
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

//终端用户本地生成二维码,用于电站转让直接扫描
-(void)createInviationCode
{
    NSString *email = [PrivateMange share].currentUser.email;
    NSDictionary *emailDic = @{@"email":email};
    NSData *data = [[emailDic yy_modelToJSONString] dataUsingEncoding:NSUTF8StringEncoding];
    NSString *base64Str = [data base64EncodedStringWithOptions:0];
    [self genarateQRCodeWithContent:base64Str];
    
}

/**
  *  根据CIImage生成指定大小的UIImage
  *
 *  @param image CIImage
 *  @param size  图片宽度
  */
 - (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
     CGRect extent = CGRectIntegral(image.extent);
     CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
     // 1.创建bitmap;
     size_t width = CGRectGetWidth(extent) * scale;
   size_t height = CGRectGetHeight(extent) * scale;
     CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
     CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
     CIContext *context = [CIContext contextWithOptions:nil];
     CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
     CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
     CGContextScaleCTM(bitmapRef, scale, scale);
     CGContextDrawImage(bitmapRef, extent, bitmapImage);

     // 2.保存bitmap到图片
     CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
     CGContextRelease(bitmapRef);
     CGImageRelease(bitmapImage);
     return [UIImage imageWithCGImage:scaledImage];
 }

#pragma mark ------- 生成二维码 -------
-(void)genarateQRCodeWithContent:(NSString*)content
{
    if(content.length == 0)return;
   
    NSDictionary *codeDic = @{
        @"QRCode":content,
        @"userType":[NSString stringWithFormat:@"%ld",(NSInteger)[PrivateMange share].currentUser.hierarchyCode],
        @"extend":@""
    };
    
    NSData *data = [[codeDic yy_modelToJSONString] dataUsingEncoding:NSUTF8StringEncoding];
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [filter setValue:data forKey:@"inputMessage"];
    [filter setValue:@"H" forKey:@"inputCorrectionLevel"];
    
//    CIFilter* color_filter = [CIFilter filterWithName:@"CIFalseColor"];
//
//    [color_filter setDefaults];
//
//    [color_filter setValue:filter.outputImage forKey:@"inputImage"];
//
//    //设置二维码的颜色（二维码都是由2个颜色组成，可自行改变尝试效果）
//
//    [color_filter setValue:[CIColor colorWithRed:86/255.0 green:194/255.0 blue:113/255.0] forKey:@"inputColor0"];
//
//    [color_filter setValue:[CIColor greenColor]forKey:@"inputColor1"];

    
    UIImage *image = [self createNonInterpolatedUIImageFormCIImage:filter.outputImage withSize:150];
    
    UIImage *logo = [UIImage imageNamed:@"QR_logo"];
    
    UIImage *logoQRImage = [self addLogo:image logo:logo];
    
    self.qrCodeImageView.image = logoQRImage;
}


//二维码中间插入小插图
-(UIImage*)addLogo:(UIImage *)ori_img logo:(UIImage*)logo_img
{
    UIGraphicsBeginImageContextWithOptions(ori_img.size,NO,[[UIScreen mainScreen]scale]);
    //将二维码的图片画入
    [ori_img drawInRect:CGRectMake(0, 0, ori_img.size.width, ori_img.size.height)];
    
    UIImage *centerImg = logo_img;
    
    CGFloat centerW = ori_img.size.width*0.3;
    
    CGFloat centerH = centerW;
    
    CGFloat centerX = (ori_img.size.width-centerW)*0.5;
    
    CGFloat centerY = (ori_img.size.height-centerH)*0.5;
    
    [centerImg drawInRect:CGRectMake(centerX, centerY, centerW, centerH)];
   
    //5.3获取绘制好的图片
    
    UIImage *finalImg = UIGraphicsGetImageFromCurrentImageContext();
    
    //5.4关闭图像上下文
    
    UIGraphicsEndImageContext();
    
    return finalImg;
    
}
@end
